package routerServer

import (
	"crypto/tls"
	"github.com/gin-gonic/gin"
	"go-fox-edge-iot-gateway/commEnv"
	"io"
	"net/http"
)

var (
	engine *gin.Engine
	server *routerServer
	router *routerHandler
)

func init() {
	// 禁止打印日志：将日志输出，重定向到一个空的位置
	gin.SetMode(gin.DebugMode)
	gin.DefaultWriter = io.MultiWriter()

	engine = gin.Default()
	engine.Use(corsGin()) // 应用 CORS 中间件到所有路由

	router = &routerHandler{}
	router.router = make(map[string]interface{})
	router.tls = &http.Transport{ // 创建自定义的Transport，跳过证书验证（仅用于测试）
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
}

func StartServer() {
	// 启动服务
	go server.startServer(commEnv.Service.CertFile, commEnv.Service.KeyFile)
}

// 跨域配置
func corsGin() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
